package com.hytc.controller;

import com.hytc.entity.Cart;
import com.hytc.entity.User;
import com.hytc.service.UserService;
import com.hytc.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class SessionServlet extends HttpServlet {
    private UserService service = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        /**
         * 获取用户名密码 添加到session
         */
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = service.login(username, password);
        if (user != null) {
            Cookie cookie = new Cookie("username", username);
            Cookie cookie1 = new Cookie("password", password);
            cookie.setMaxAge(60 * 60);
            cookie1.setMaxAge(60 * 60);
            resp.addCookie(cookie);
            resp.addCookie(cookie1);
            HttpSession session = req.getSession();
            List<User> userList = new ArrayList<>();
            userList.add(user);
            session.setAttribute("user", user);
            session.setAttribute("userList", userList);


            /**
             * 计算商品总价
             */
            User user1 = (User) session.getAttribute("user");
            if (user1 != null) {
                List<Cart> cart = service.cart(user.getId());
                double sum1 = 0;
                double sum2 = 0;
                for (Cart cartItem : cart) {
                    sum1 += cartItem.getBuy_price(); // 折扣金额
                    sum2 += cartItem.getPrice(); // 总金额
                }

                // 存储金额信息到会话中
                session.setAttribute("sum1", sum1 - sum2); // 折扣金额
                session.setAttribute("sum2", sum2); // 总金额
                session.setAttribute("cart", cart); // 购物车列表



                String contextPath = this.getServletContext().getContextPath();
                resp.sendRedirect(contextPath + "/login_success.jsp");

            } else {
                resp.setContentType("text/html;charset=utf-8");
                resp.sendRedirect("/login.jsp");
            }


        }
    }
}
//
//    @Override
//    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//
//    }
//}
